package com.hzp.tool.common.ui.component;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;

/**
 * @author Huang Zhaoping
 * @date 2019/3/8
 */
public class PropertyComponent extends Component {

    private Component component;
    private String defaultProperty;

    public PropertyComponent(Component component, String defaultProperty) {
        if (defaultProperty == null) defaultProperty = "";
        this.component = component;
        this.defaultProperty = defaultProperty;
    }

    public String getProperty() {
        String property = defaultProperty;
        if (component instanceof JTextComponent) {
            property = ((JTextComponent) component).getText();
        } else if (component instanceof TextComponent) {
            property = ((TextComponent) component).getText();
        } else if (component instanceof AbstractButton) {
            property = String.valueOf(((AbstractButton) component).isSelected());
        }
        return property == null ? defaultProperty : property.trim();
    }

    public void setProperty(String property) {
        if (property == null || property.length() == 0) property = defaultProperty;
        if (component instanceof JTextComponent) {
            ((JTextComponent) component).setText(property);
        } else if (component instanceof TextComponent) {
            ((TextComponent) component).setText(property);
        } else if (component instanceof AbstractButton) {
            ((AbstractButton) component).setSelected(Boolean.valueOf(property));
        }
    }
}
